<template>
  <div ref="chartRef" style="width: 100%; height: 100%;" />
</template>
<script setup lang="ts">
import { type PropType, ref, computed, watch } from "vue";
import { useDark, useECharts } from "@pureadmin/utils";
import { arrSum } from "@/utils/functions";
const props = defineProps({
  data: {
    type: Array as PropType<Array<number>>,
    default: () => []
  },
  color: {
    type: String,
    default: () => []
  }
});
const { isDark } = useDark();

const theme = computed(() => (isDark.value ? "dark" : "light"));

const chartRef = ref();
const { setOptions } = useECharts(chartRef, {
  theme,
  renderer: "svg"
});
watch(
  () => isDark.value,
  () => {
    getinit();
  }
);
watch(
  () => props.data,
  data => {
    getinit();
  }
);


const getinit = () => {
  setOptions({
    container: ".pie",
    tooltip: {
      trigger: "item",
      formatter: (params) => `<div class='dians' style=background-color:${params.color};></div>${params.name}  ${params.value}个`
    },
    title: {
      text: arrSum(props.data, 'value').toFixed(0),
      // 副标题
      subtext: "告警总数",
      // 主副标题间距
      itemGap: 8,
      x: "center",
      y: "center",
      // 主标题样式
      textStyle: {
        fontSize: "1rem",
        color: isDark.value ? "#fff" : "#000"
      },
      // 副标题样式
      subtextStyle: {
        fontSize: "1rem"
      }
    },
    legend: {
      icon: "circle",
      itemHeight: 10,
      itemWidth: 10,
      bottom: 0,
      align: "auto",
      top: "center",
      right: "5%",
      orient: "vertical",
      data: props.data,
      formatter: function (name) {
        //通过name获取到数组对象中的单个对象
        let singleData = props.data.filter(function (item) {
          return item.name == name;
        });
        return name + '   ' + singleData[0]?.value;
      },
      textStyle: {
        fontSize: 14,
        color: isDark.value ? "#fff" : "#000"
      }
    },
    series: [
      {
        data: props.data,
        name: "告警统计",
        type: "pie",
        top: "0",
        left: "center",
        radius: ["70%", "90%"],
        center: ["50%", "50%"],
        color: props.color,
        label: {
          show: false,
          formatter: "{b}: {c} ({d}%)" // b是数据项名称，c是数值，d是百分比
        }
      }
    ]
  });
};
getinit();
</script>
<style lang="scss" scoped>
.dians {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  /* background-color: #ecbc73; */
  margin-right: 5px;
  display: inline-block;
  position: relative;
  bottom: 2px;
}
</style>
